import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useNavigate, Link } from 'react-router-dom';

import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI
import ReviewerListABI from '../contract/ABIs/ReviewerList.json'; // 审核员列表合约 ABI
import AdminListABI from '../contract/ABIs/AdminList.json'; // 管理员列表合约 ABI
import UserABI from '../contract/ABIs/User.json'; // 用户合约 ABI
import ReviewerABI from '../contract/ABIs/Reviewer.json'; // 审核员合约 ABI
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI


import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
import ReviewerListAddress from '../contract/ADDRESSes/ReviewerListAddress'; // 审核员列表合约地址
import AdminListAddress from '../contract/ADDRESSes/AdminListAddress'; // 管理员列表合约地址
// import '../static/css/app.css'; // 导入 CSS 文件
import $ from 'jquery';
// import '../static/logincss/css/login.css';
import logosm from '../static/bootstrap/images/logo-sm.svg'



const Login = () => {
    const [web3, setWeb3] = useState(null);
    const [contractUserList, setContractUserList] = useState(null);
    const [contractReviewerList, setcontractReviewerList] = useState(null);
    const [contractAdminList, setcontractAdminList] = useState(null);


    const [userName, setUserName] = useState('');
    const [password, setPassword] = useState('');
    const [role, setRole] = useState('1'); // 默认角色为用户
    const navigate = useNavigate();


    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);


                    // 创建用户列表合约实例
                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);

                    // 创建审核员列表合约实例
                    const reviewerListInstance = new web3Instance.eth.Contract(
                        ReviewerListABI,
                        ReviewerListAddress
                    );
                    setcontractReviewerList(reviewerListInstance);

                    // 创建管理员列表合约实例
                    const adminListInstance = new web3Instance.eth.Contract(
                        AdminListABI,
                        AdminListAddress
                    );
                    setcontractAdminList(adminListInstance);

                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, []);


    // 清除先前的账号密码
    const clearInputs = () => {
        setUserName('');
        setPassword('');
    };

    // 登录处理
    const handleLogin = async (loginFunction) => {
        try {
            await loginFunction();
            clearInputs();
            // Add any additional logic after successful login here
        } catch (error) {
            console.error(error);
            alert('登录失败，请重试！');
        }
    };

    // 用户登录函数
    const LoginUser = async () => {
        if (contractUserList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress, "Input:", userName, password);
                // 获取用户合约地址
                const UserAddress = await contractUserList.methods.getUserAddress(fromAddress).call();
                console.log("用户合约地址:", UserAddress);
                // 调用用户列表合约的 isNotRegistered，verifyPwd 函数
                const isFull = await contractUserList.methods.isUser(UserAddress).call({ from: fromAddress });
                if (isFull) {
                    const verifyPwd = await contractUserList.methods.verifyPassword(userName, password).call({ from: fromAddress });
                    if (verifyPwd) {
                        // 部署用户合约
                        const userContract = new web3.eth.Contract(UserABI, UserAddress);
                        console.log("部署后的用户合约:", userContract);
                        // const userInfo = await userContract.methods.getOwnerInfo().call({ from: fromAddress });
                        // console.log("用户信息:", userInfo)
                        alert('用户登录成功！');
                        navigate(`/user/${UserAddress}`);
                    } else {
                        alert('学号或密码错误！');
                    }
                } else {
                    alert('用户未注册！')
                }
            } catch (error) {
                console.error(error);
                alert('用户登录失败！');
            }
        }
    };

    // 审核员登录函数
    const LoginReviewer = async () => {
        if (contractReviewerList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress, "Input:", userName, password);
                // 获取审核员合约地址
                const ReviewerAddress = await contractReviewerList.methods.getReviewerAddress(fromAddress).call();
                console.log("ReviewerAddress:", ReviewerAddress);
                const isFull = await contractReviewerList.methods.isNotRegistered(ReviewerAddress).call();
                if (isFull) {
                    // 调用审核员列表合约的 isNotRegistered，verifyPwd 函数
                    const verifyPwd = await contractReviewerList.methods.verifyPwd(userName, password).call({ from: fromAddress });
                    if (verifyPwd) {
                        // 部署审核员合约
                        const reviewerContract = new web3.eth.Contract(ReviewerABI, ReviewerAddress);
                        console.log("部署后的审核员合约:", reviewerContract);
                        alert('审核员登录成功！');
                        navigate(`/reviewer/${ReviewerAddress}`);
                    } else {
                        alert('账号或密码错误！');
                    }
                } else {
                    alert('审核员未注册！')
                }
            } catch (error) {
                console.error(error);
                alert('审核员登录失败！');
            }
        }
    };

    // 管理员登录函数
    const LoginAdmin = async () => {
        if (contractAdminList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress, "Input:", userName, password);
                // 获取管理员合约地址
                const AdminAddress = await contractAdminList.methods.getAdminAddress(fromAddress).call();
                console.log("ReviewerAddress:", AdminAddress);
                const isFull = await contractAdminList.methods.isNotRegistered(AdminAddress).call();
                if (isFull) {
                    // 调用管理员列表合约的 isNotRegistered，verifyPwd 函数
                    const verifyPwd = await contractAdminList.methods.verifyPwd(userName, password).call({ from: fromAddress });
                    if (verifyPwd) {
                        // 部署管理员合约
                        const adminContract = new web3.eth.Contract(AdminABI, AdminAddress);
                        console.log("部署后的管理员合约:", adminContract);
                        alert('管理员登录成功！');
                        navigate(`/admin/${AdminAddress}`);
                    } else {
                        alert('账号或密码错误！');
                    }
                } else {
                    alert('管理员未注册！')
                }
            } catch (error) {
                console.error(error);
                alert('管理员登录失败！');
            }
        }
    };

    return (
        <div >
            <div className="container"  >
                <div className="row justify-content-center">
                    <div className="col-xxl-4 col-xl-4 col-lg-5 col-md-6 col-sm-6 col-12">
                        <form
                            action="#"
                            className="my-5"
                        >
                            <div className="card p-md-4 p-sm-3">
                                <div className="login-form">
                                    <a
                                        className="mb-4 d-flex"
                                        href="index.html"
                                    >
                                        <img
                                            alt="Bootstrap Gallery"
                                            className="img-fluid login-logo"
                                            src={logosm}
                                        />
                                    </a>
                                    <h3 className="mt-5 mb-4">
                                        Login
                                    </h3>
                                    <div className="mb-3">
                                        <label className="form-label">
                                            你的身份
                                        </label>
                                        {/* <input
                                            className="form-control"
                                            placeholder="Enter your email"
                                            type="text"
                                        /> */}
                                        <select className="form-control" value={role} onChange={(e) => setRole(e.target.value)}
                                            style={{ background: '#242627', border: '1px solid #ced4da', borderRadius: '0.25rem' }}>
                                            <option value="1">请选择身份</option>
                                            <option value="user">用户</option>
                                            <option value="reviewer">审核员</option>
                                            <option value="admin">管理员</option>
                                        </select>
                                    </div>
                                    {/* 默认的 */}
                                    {role === '1' && (
                                        <div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的用户名
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入用户名"
                                                    type="text"
                                                    value={userName} onChange={(e) => setUserName(e.target.value)}
                                                />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的密码
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入密码"
                                                    type="password"
                                                    value={password} onChange={(e) => setPassword(e.target.value)}
                                                />
                                            </div>

                                            <div className="d-flex align-items-center justify-content-between">
                                                <div className="form-check m-0">
                                                    <input
                                                        className="form-check-input"
                                                        defaultValue=""
                                                        id="rememberPassword"
                                                        type="checkbox"
                                                    />
                                                    <label
                                                        className="form-check-label"
                                                        htmlFor="rememberPassword"
                                                    >
                                                        Remember
                                                    </label>
                                                </div>
                                                <a
                                                    className="text-primary text-decoration-underline"
                                                    href="forgot-password.html"
                                                >
                                                    Lost									password?
                                                </a>
                                            </div>
                                            <div className="d-grid py-3 mt-3">
                                                <button
                                                    className="btn btn-lg btn-primary"
                                                    type="button"
                                                    onClick={() => handleLogin(LoginUser)}
                                                >
                                                    LOGIN
                                                </button>
                                            </div>
                                        </div>
                                    )}
                                    {/* 用户 */}
                                    {role === 'user' && (
                                        <div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的学号
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入学号"
                                                    type="text"
                                                    value={userName} onChange={(e) => setUserName(e.target.value)}
                                                />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的密码
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入密码"
                                                    type="password"
                                                    value={password} onChange={(e) => setPassword(e.target.value)}
                                                />
                                            </div>

                                            <div className="d-flex align-items-center justify-content-between">
                                                <div className="form-check m-0">
                                                    <input
                                                        className="form-check-input"
                                                        defaultValue=""
                                                        id="rememberPassword"
                                                        type="checkbox"
                                                    />
                                                    <label
                                                        className="form-check-label"
                                                        htmlFor="rememberPassword"
                                                    >
                                                        Remember
                                                    </label>
                                                </div>
                                                <a
                                                    className="text-primary text-decoration-underline"
                                                    href="forgot-password.html"
                                                >
                                                    Lost									password?
                                                </a>
                                            </div>
                                            <div className="d-grid py-3 mt-3">
                                                <button
                                                    className="btn btn-lg btn-primary"
                                                    type="button"
                                                    onClick={() => handleLogin(LoginUser)}
                                                >
                                                    LOGIN
                                                </button>
                                            </div>
                                        </div>
                                    )}
                                    {/* 审核员 */}
                                    {role === 'reviewer' && (
                                        <div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的用户名
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入用户名"
                                                    type="text"
                                                    value={userName} onChange={(e) => setUserName(e.target.value)}
                                                />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的密码
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入密码"
                                                    type="password"
                                                    value={password} onChange={(e) => setPassword(e.target.value)}
                                                />
                                            </div>

                                            <div className="d-flex align-items-center justify-content-between">
                                                <div className="form-check m-0">
                                                    <input
                                                        className="form-check-input"
                                                        defaultValue=""
                                                        id="rememberPassword"
                                                        type="checkbox"
                                                    />
                                                    <label
                                                        className="form-check-label"
                                                        htmlFor="rememberPassword"
                                                    >
                                                        Remember
                                                    </label>
                                                </div>
                                                <a
                                                    className="text-primary text-decoration-underline"
                                                    href="forgot-password.html"
                                                >
                                                    Lost									password?
                                                </a>
                                            </div>
                                            <div className="d-grid py-3 mt-3">
                                                <button
                                                    className="btn btn-lg btn-primary"
                                                    type="button"
                                                    onClick={() => handleLogin(LoginReviewer)}
                                                >
                                                    LOGIN
                                                </button>
                                            </div>
                                        </div>
                                    )}
                                    {/* 管理员 */}
                                    {role === 'admin' && (
                                        <div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的用户名
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入用户名"
                                                    type="text"
                                                    value={userName} onChange={(e) => setUserName(e.target.value)}
                                                />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label">
                                                    你的密码
                                                </label>
                                                <input
                                                    className="form-control"
                                                    placeholder="请输入密码"
                                                    type="password"
                                                    value={password} onChange={(e) => setPassword(e.target.value)}
                                                />
                                            </div>

                                            <div className="d-flex align-items-center justify-content-between">
                                                <div className="form-check m-0">
                                                    <input
                                                        className="form-check-input"
                                                        defaultValue=""
                                                        id="rememberPassword"
                                                        type="checkbox"
                                                    />
                                                    <label
                                                        className="form-check-label"
                                                        htmlFor="rememberPassword"
                                                    >
                                                        Remember
                                                    </label>
                                                </div>
                                                <a
                                                    className="text-primary text-decoration-underline"
                                                    href="forgot-password.html"
                                                >
                                                    Lost									password?
                                                </a>
                                            </div>
                                            <div className="d-grid py-3 mt-3">
                                                <button
                                                    className="btn btn-lg btn-primary"
                                                    type="button"
                                                    onClick={() => handleLogin(LoginAdmin)}
                                                >
                                                    LOGIN
                                                </button>
                                            </div>
                                        </div>
                                    )}
                                    <div className="text-center py-2">
                                        or Login with
                                    </div>
                                    <div className="btn-group w-100">
                                        <button
                                            className="btn btn-sm btn-outline-danger"
                                            type="button"
                                        >
                                            Google
                                        </button>
                                        <button
                                            className="btn btn-sm btn-outline-primary"
                                            type="button"
                                        >
                                            Facebook
                                        </button>
                                        <button
                                            className="btn btn-sm btn-outline-info"
                                            type="button"
                                        >
                                            Twitter
                                        </button>
                                    </div>
                                    <div className="text-center pt-4">
                                        <span>
                                            Not registered?
                                        </span>
                                        <Link to={`/register`}
                                            className="text-primary text-decoration-underline"
                                        >
                                            没有注册，请注册
                                        </Link>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

        </div>

    );
}

export default Login;